<template>
  <main-card title="模型训练" :show-screen-space="false" :online-lab="true">
    <template #tool-btn>
      <a-button type="text" @click="changeTaskListOptions({ open: true })">
        <i class="iconfont icon-tasklist-line" style="font-size: 18px"></i>
      </a-button>
      <a-button type="primary" @click="goCreateTask">创建任务</a-button>
    </template>

    <div class="mb-44 fbc gap-x-8">
      <!-- <a-select v-model:value="pageForm.typeId" class="w-140" :options="taskTypeOptions" @change="getDataList({ offset: 1 })" /> -->
      <a-select v-model:value="pageForm.trainStatus" class="w-140" :options="taskStatusOptions" @change="getDataList({ offset: 1 })" />
      <!-- <a-select v-model:value="pageForm.deployStatus" class="w-140" :options="serviceStatusOptions" @change="getDataList({ offset: 1 })" /> -->

      <div class="flex-1"></div>
      <a-input
        v-model:value="pageForm.name"
        v-trim
        class="h-36"
        allow-clear
        placeholder="请输入任务名称"
        style="width: 328px"
        @keyup.enter="getDataList({ offset: 1 })"
      >
        <template #prefix> <i class="iconfont icon-search-line"></i> </template>
      </a-input>
    </div>

    <a-table
      :data-source="dataList"
      :columns="taskTableColumns"
      :pagination="false"
      :custom-row="r => ({ onClick: () => handleToDetail(r) })"
      :loading="loading"
      @change="tableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'typeId'">
          {{ getTaskTypeOptions(record.typeId)?.label }}
        </template>
        <template v-else-if="column.dataIndex === 'trainStatus'">
          <div class="table__status" :class="[getTrainingStatusObj(record.trainStatus).className]">
            {{ getTrainingStatusObj(record.trainStatus).text }}
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'deployStatus'">
          <div class="table__status" :class="[getDeployStatusObj(record.deployStatus).className]">
            {{ getDeployStatusObj(record.deployStatus).text }}
          </div>
        </template>
        <template v-else-if="column.dataIndex == 'tools'">
          <a-dropdown placement="bottom" @click.stop>
            <a-button type="text" class="icon-only-btn" :data-share="record?.createType === 1" @click.stop>
              <i class="iconfont icon-more-line"></i>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item
                  class="menu-icon-item"
                  :disabled="record.trainStatus !== TrainingStatus.Success"
                  @click="reName(record as TaskDetail)"
                >
                  重命名
                </a-menu-item>
                <a-menu-item
                  class="menu-icon-item"
                  :disabled="record.trainStatus !== TrainingStatus.Success"
                  @click="stopTask(record as TaskDetail)"
                >
                  停止任务
                </a-menu-item>
                <a-menu-item class="menu-icon-item" @click="modelPublish(record as any)"> 模型发布 </a-menu-item>
                <a-menu-item
                  class="menu-icon-item"
                  :disabled="record.trainStatus !== TrainingStatus.Success"
                  @click="localExport(record.id)"
                >
                  本地导出
                </a-menu-item>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly)"
                  class="menu-icon-item"
                  @click="openDelDialog(record)"
                >
                  删除任务
                </a-menu-item>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly)"
                  class="menu-icon-item"
                  @click.stop="handleOpenShareModal(record)"
                >
                  分享
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </template>
    </a-table>
    <g-pagination
      v-model:offset="pageForm.offset"
      v-model:limit="pageForm.limit"
      class="mt-32"
      :total="pageForm.total"
      @change="getDataList"
    />
  </main-card>

  <online-export-from ref="onLineExportRef" v-model:show="showLineExport" :loading="okBtnLoading" @submit="onLineExportSubmit" />

  <model-publish-modal ref="modelPublishRef" />

  <!-- 删除确认弹窗  -->
  <delete-confirm-dialog v-model:show="deleteDialog" :loading="confirmLoading" :confirm-name="deleteName" @ok="onClickDelete" />

  <share-modal
    ref="shareModalRef"
    :submit-api="modelTrainingApi.share"
    :remove-user-api="modelTrainingApi.removeShareUser"
    :get-list-api="modelTrainingApi.getShareList"
  />

  <a-modal v-model:open="reNameVisible" :title="'重命名'" centered :width="416" :ok-text="'创建'" @ok="saveReName">
    <a-form ref="reNameFormRef" layout="vertical" :model="reNameFormState">
      <a-form-item label="模型名称" name="name" :rules="[{ required: true, message: '请输入模型名称', trigger: 'change' }]">
        <g-input v-model:value="reNameFormState.name" placeholder="请输入模型名称" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { message, Modal, TableProps } from 'ant-design-vue'
  import { onMounted, ref } from 'vue'
  import { createVNode } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import GPagination from '@/components/GPagination/index.vue'
  import WarnIcon from '@/components/icon/IconWarn/index.vue'
  import ShareModal from '@/components/ShareModal/index.vue'
  import useList from '@/hooks/use-list'
  import { modelTrainingApi } from '@/services/api'
  import { filterTableColumns } from '@/utils'
  import { checkPermissions } from '@/utils/share'

  import ModelPublishModal from '../components/ModelPublishModal.vue'
  import OnlineExportFrom from '../components/OnlineExportFrom.vue'
  import { useTaskListDrawerStore } from '../components/TaskListDrawer/store'
  import { serviceStatusList, taskStatusList, taskTypeList } from '../options'
  import { DeployStatus, TaskDetail, TrainingStatus } from '../types'
  import { getDeployStatusObj, getTaskTypeOptions, getTrainingStatusObj } from '../utils'

  /* 下拉框筛选项------------------------------------------------------------------------ */
  // const taskTypeOptions = [
  //   {
  //     label: '全部类型',
  //     value: ''
  //   },
  //   ...taskTypeList
  // ]
  // const serviceStatusOptions = [
  //   {
  //     label: '全部服务状态',
  //     value: ''
  //   },
  //   ...serviceStatusList
  // ]
  const taskStatusOptions = [
    {
      label: '全部状态',
      value: ''
    },
    ...taskStatusList
  ]
  /* --------------------------------------------------------------------------------- */

  const router = useRouter()

  interface PageForm {
    columns: string
    name: string
    order: string
    // 任务类型
    typeId: string
    // 任务状态
    trainStatus: string
    // 服务状态
    deployStatus: string
  }

  const { pageForm, dataList, loading, getDataList } = useList<PageForm, TaskDetail[]>(modelTrainingApi.list, {
    name: '',
    order: 'desc',
    columns: 'createTime',
    typeId: '',
    trainStatus: '',
    deployStatus: ''
  })

  let taskTableColumns = ref(
    filterTableColumns([
      {
        title: '任务名称',
        width: 180,
        dataIndex: 'name'
      },
      {
        title: '模型名称',

        dataIndex: 'modelName'
      },
      {
        title: '耗时',
        width: 200,
        dataIndex: 'trainStatus'
      },
      {
        title: '状态',
        width: 200,
        dataIndex: 'deployStatus'
      },
      {
        title: '创建时间',
        width: 200,
        dataIndex: 'createTime',
        isSort: true
      },
      {
        title: '操作',
        width: 63,
        dataIndex: 'tools'
      }
    ])
  )

  const goCreateTask = () => {
    router.push('/modal-training/add')
  }

  const handleToDetail = (row: TaskDetail) => {
    router.push(`/modal-training/detail/${row.id}`)
  }

  // 表格变化
  const tableChange: TableProps<any>['onChange'] = (pagination, filters, sorter: any) => {
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    pageForm.value.columns = sorter.field
    if (!sorter.order) {
      pageForm.value.columns = 'createTime'
      pageForm.value.order = 'desc'
    }
    getDataList({ offset: 1 })
  }

  /* 在线导出------------------------------------------------------------------------------------- */
  const { changeTaskListOptions } = useTaskListDrawerStore()

  const showLineExport = ref(false)
  const onLineExportRef = ref<InstanceType<typeof OnlineExportFrom>>()

  const { loading: okBtnLoading, runAsync: runOnlineExport } = useRequest(modelTrainingApi.onlineExport)
  const onLineExportSubmit = async (formData: any) => {
    await runOnlineExport(formData)
    showLineExport.value = false
    changeTaskListOptions({ open: true, key: '1' })
  }
  const onLineExport = (record: TaskDetail) => {
    onLineExportRef.value?.setFormState(record)
    showLineExport.value = true
  }

  // 模型发布
  const modelPublishRef = ref()
  const modelPublish = (item: TaskDetail) => {
    console.log('模型发布', item)

    modelPublishRef.value?.open()
  }

  /* 重命名------------------------------------------------------------------------------------- */
  const reNameVisible = ref(false)
  const reNameFormRef = ref()
  const reNameFormState = ref({ name: '' })
  const reName = (item: TaskDetail) => {
    console.log('模型重命名', item)
    reNameVisible.value = true
    reNameFormState.value.name = item.name
  }
  const saveReName = async () => {
    await reNameFormRef.value?.validateFields()
    console.log('表单校验成功, 提交表单', reNameFormState)
  }

  /* 本地导出------------------------------------------------------------------------------------- */

  const localExport = async (recordId: string) => {
    await modelTrainingApi.localExport({}, { urlParams: { id: recordId } })
    changeTaskListOptions({ open: true, key: '2' })
  }

  /*----------------------------------------- 分享 --------------------------------*/
  const shareModalRef = ref<InstanceType<typeof ShareModal>>()
  const handleOpenShareModal = (item: any) => {
    shareModalRef.value?.open({
      id: item.id
    })
  }

  /* 删除逻辑------------------------------------------------------------------------------------------------------------- */
  const deleteId = ref<string>('')
  const deleteDialog = ref<boolean>(false)
  const deleteName = ref<string>('')
  const openDelDialog = (row: any) => {
    deleteDialog.value = true
    deleteName.value = row.name
    deleteId.value = row.id
  }
  const { loading: confirmLoading, runAsync: runDelModelTraining } = useRequest(modelTrainingApi.del)
  const onClickDelete = async () => {
    await runDelModelTraining({}, { urlParams: { id: deleteId.value } })
    deleteDialog.value = false
    message.success('删除成功')
    getDataList({ offset: 1 })
  }

  /* 部署逻辑------------------------------------------------------------------------------------------------------------- */
  const { loading: isDeployLoading, runAsync: runDeployTask } = useRequest(modelTrainingApi.deploy, {
    onSuccess: () => {
      message.success('操作成功')
      getDataList({ offset: 1 })
    }
  })

  const deployTask = (record: TaskDetail) => {
    if ([DeployStatus.NotDeployed].includes(record.deployStatus)) {
      Modal.confirm({
        icon: createVNode(WarnIcon),
        title: `请确认是否部署此任务服务？`,
        okButtonProps: {
          type: 'default',
          loading: isDeployLoading.value
        },
        centered: true,
        onOk: () => {
          runDeployTask({ id: record.id })
        }
      })
    } else if ([DeployStatus.ToBeDeployed, DeployStatus.Deploying].includes(record.deployStatus)) {
      Modal.warning({
        icon: createVNode(WarnIcon),
        title: `服务正在部署，请耐心等待`,
        okButtonProps: {
          type: 'default'
        },
        centered: true
      })
    } else if (
      [
        DeployStatus.DeploymentSuccessful,
        DeployStatus.DeploymentFailed,
        DeployStatus.DeploymentTimeout,
        DeployStatus.DeploymentPastDue
      ].includes(record.deployStatus)
    ) {
      Modal.confirm({
        icon: createVNode(WarnIcon),
        title: `请确认是否重新部署此任务服务？`,
        okButtonProps: {
          type: 'default',
          loading: isDeployLoading.value
        },
        centered: true,
        onOk: async () => {
          runDeployTask({ id: record.id })
        }
      })
    }
  }

  /* 预测逻辑------------------------------------------------------------------------------------------------------------- */
  const { runAsync: runForecastTask } = useRequest(modelTrainingApi.forecast)

  const stopTask = async (record: TaskDetail) => {
    Modal.confirm({
      icon: createVNode(WarnIcon),
      title: `此任务将停止训练，请确认操作`,
      okButtonProps: {
        type: 'default',
        loading: isDeployLoading.value
      },
      centered: true,
      onOk: () => {
        console.log('停止任务')
      }
    })
    // if ([DeployStatus.NotDeployed].includes(record.deployStatus)) {
    //   Modal.confirm({
    //     icon: createVNode(WarnIcon),
    //     title: `此服务暂未部署，无法使用预测功能，请您先部署该任务服务`,
    //     okButtonProps: {
    //       type: 'default',
    //       loading: isDeployLoading.value
    //     },
    //     okText: '部署',
    //     centered: true,
    //     onOk: () => {
    //       runDeployTask({ id: record.id })
    //     }
    //   })
    // } else if ([DeployStatus.ToBeDeployed, DeployStatus.Deploying].includes(record.deployStatus)) {
    //   Modal.warning({
    //     icon: createVNode(WarnIcon),
    //     title: `服务正在部署，请耐心等待`,
    //     okButtonProps: {
    //       type: 'default'
    //     },
    //     centered: true
    //   })
    // } else if (
    //   [DeployStatus.DeploymentFailed, DeployStatus.DeploymentTimeout, DeployStatus.DeploymentPastDue].includes(record.deployStatus)
    // ) {
    //   Modal.confirm({
    //     icon: createVNode(WarnIcon),
    //     title: `任务无法预测，请您重新部署该任务服务`,
    //     okButtonProps: {
    //       type: 'default',
    //       loading: isDeployLoading.value
    //     },
    //     centered: true,
    //     okText: '重新部署',
    //     onOk: async () => {
    //       runDeployTask({ id: record.id })
    //     }
    //   })
    // } else if ([DeployStatus.DeploymentSuccessful].includes(record.deployStatus)) {
    //   await runForecastTask(
    //     {},
    //     {
    //       urlParams: {
    //         id: record.id
    //       }
    //     }
    //   )
    //   router.push(`/modal-training/predicted/${record.id}`)
    // }
  }
  /* ------------------------------------------------------------------------------------------------------------- */

  onMounted(() => {
    getDataList()
  })
</script>
